package com.yz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yz.core.utils.PasswordUtils;
import com.yz.core.utils.UUIDUtils;
import com.yz.entity.UserEntity;
import com.yz.mapper.UserMapper;
import com.yz.service.UserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @className: UserServiceImpl
 * @author: shuishui
 * @date: 2022/12/03 8:52
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,UserEntity> implements UserService {

    public void register(UserEntity userEntity){
        userEntity.setPassword(PasswordUtils.hashPw(userEntity.getPassword()));
        userEntity.setStatus(1);
        userEntity.setCreateTime(new Date());
        userEntity.setActivationCode(UUIDUtils.getId());
        userEntity.setType(0);
        int save = baseMapper.insert(userEntity);
    }
    public UserEntity byActivationCode(String activationCode){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("activation_code",activationCode);
        return baseMapper.selectOne(queryWrapper);
    }

    public UserEntity login(String username, String password){
//        UserMapper baseMapper = (UserMapper) getBaseDao();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username",username);
        UserEntity userEntity = baseMapper.selectOne(queryWrapper);

        if (userEntity == null) {
            return null; // 用户名不存在
        }

        // 2、密码的比对
        if (!PasswordUtils.check(password, userEntity.getPassword())) {
            return null;
        }

        return userEntity;
    }

    public void updateHeaderUrl(Integer id, String filePath){
        baseMapper.updateHeaderUrl(id,filePath);
    }

    @SneakyThrows
    public boolean changePassword(Map mapp, Integer id) {
//        UserMapper baseMapper = (UserMapper) getBaseDao();
        UserEntity userEntity = baseMapper.selectById(id);
        String password =  PasswordUtils.hashPw(mapp.get("oldPassword").toString());
        boolean result = PasswordUtils.check(password,userEntity.getPassword());
        if (!result){
            return false;
        }
        String newPassword = mapp.get("newPassword").toString();
        Integer result2 = baseMapper.changePassword(id,newPassword);
        if (result2==null){
            return false;
        }
        return true;
    }

}
